<?php

namespace app\controller\wmapi;

use Illuminate\Support\Facades;
use Illuminate\Support\Facades\Validator;
use plugin\admin\app\common\Util;
use plugin\admin\app\model\Admin;
use support\Request;
use app\model\WaAdmins;
use app\model\WaRoles;
use app\model\WaRules;
use app\model\WaDepartment;
use Illuminate\Support\Facades\DB;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Facades\Cache;
use Tinywan\Validate\Validate;

class AdminController extends Validate
{
    /**
     * 账户管理-列表
     * @param Request $request
     * @return mixed
     */
    public function adminList(Request $request)
    {
//        process($request);
        $param = $request->all();
        $condition = [];
        $between = [];
        if ($param['username']) {
            $condition [] = ['admin.username', 'like', '%' . $param['username'] . '%'];
        }
        if ($param['nickname']) {
            $condition [] = ['admin.nickname', 'like', '%' . $param['nickname'] . '%'];
        }

        if ($param['mobile']) {
            $condition [] = ['admin.mobile', 'like', '%' . $param['mobile'] . '%'];
        }
        if ($param['start_time'] && $param['end_time']) {
            $between [] = [$param['start_time'], $param['end_time']];
        }
        if ($param['status'] or $param['status'] == 0) {
            $condition [] = ['admin.status', '=', intval($param['status'])];
        }else{
            $condition [] = ['admin.status', '!=', 4];
        }
        $pageNum = $param['pageNum'] ? $param['pageNum'] : 10;
        $fields = ['admin.*'];

        $page = $param['page'] ? $param['page'] : 1;
        $rule = WaAdmins::list($page, $pageNum, $fields, $condition, $between);
        return IndexController::successed($rule, '账户列表');
    }

    /**
     * @param Request $request
     * @return \support\Response
     */
    public function adminALL(Request $request)
    {
//        process($request);
        $param = $request->all();
        $fields = ['*'];
        $condition = [];
        $condition [] = ['status', '!=', 1];
        $rule = WaAdmins::all($fields, $condition);
        return IndexController::successed($rule, '管理员列表');
    }

    /**
     * 管理员-创建
     * @param Request $request
     * @return \support\Response
     */
    public function adminCreate(Request $request)
    {
//        process($request);
        $user = $request->user; //当前操作人员 信息
        $param = $request->all();
        /**
         * 验证规则
         */
        $rule = [
            'username' => 'require|max:50', // 用户名
            'nickname' => 'require|max:50', // 昵称
            'email' => 'require', // 邮箱
            'mobile' => 'require', // 手机
            'department_id' => 'require', // 所属部门id
            'role_id' => 'require', // 所属角色id
        ];
        // 验证密码
        $password = 123456;
//        if ($param['is_merchandiser']){
//            $is_merchandiser= intval($param['is_merchandiser']);
//        }else{
//            $is_merchandiser = 0;
//        }
        $data = [
            'username' => $param['username'], // 用户名
            'nickname' => $param['nickname'], // 昵称
            'password' => Util::passwordHash($password) ? Util::passwordHash($password) : '', // 密码
//            'avatar' => $param['avatar'] ? $param['avatar'] : '', // 头像
            'email' => $param['email'], // 邮箱
            'mobile' => $param['mobile'], // 手机
            'created_at' => date('Y-m-d H:i:s', time()), // 创建时间
            'status' => 0, // 禁用
            'created_pid' => $user->id, // 创建人id
            'department_id' => intval($param['department_id']), // 部门id
            'role_id' => json_encode($param['role_id']), // 角色id
            'data_permission' => intval($param['data_permission']), // 数据权限
            'is_principal' => intval($param['is_principal']), // 是否是部门负责人
//            'merchandiser_id' => intval($param['merchandiser_id']), // 绑定的跟单人员
//            'is_merchandiser' => $is_merchandiser, // 是否跟单人员 0 不是 1 是
        ];

        if (array_key_exists('nickname_abbreviation',$param)){
            $data['nickname_abbreviation'] = $param['nickname_abbreviation'];
        }
        if (array_key_exists('english_name',$param)){
            $data['english_name'] = $param['english_name'];
        }

        // 判断是否是部门负责人 (部门暂时可以没有负责人)
        if (intval($param['is_principal']) == 1){
            $condition_principal= ['department_id' => intval($param['department_id']),'is_principal' => 1];
            $is_principal = WaAdmins::find($condition_principal);
            $is_principal = json_decode($is_principal);
            if ($is_principal){
                    //去掉原来的部门负责人
                    WaAdmins::updated(['department_id' => intval($param['department_id']),'is_principal' => 1],['is_principal'=>0]);
            }
        }
//1
//        $validate = \Tinywan\Validate\Facade\Validate::rule($rule);
//        if (!$validate->check($param)) {
//            return IndexController::errored($validate->getError());
//        } else {
            $where = ['username' => $param['username']];
            $find = WaAdmins::find($where);
            $find = json_decode($find);
            if ($find) {
                return IndexController::errored('', '管理员创建失败,登录账号已存在');
            }
            $res = WaAdmins::created($data);
            if (!$res) {
                return IndexController::errored($res, '管理员创建失败');
            } else {
                return IndexController::successed($res, '管理员创建成功');
            }
//        }

    }

    /**
     * 管理员-更新
     * @param Request $request
     * @return \support\Response
     */
    public function adminEdit(Request $request)
    {
        process($request);
        $param = $request->all();
        /**
         * 验证规则
         */
//        $rule = [
//            'username' => 'require|max:50', // 用户名
//            'nickname' => 'require|max:50', // 昵称
////            'password' => 'require|max:100', // 密码
//            'email' => 'require', // 邮箱
//            'mobile' => 'require', // 手机
//            'admin_id' => 'require', // 当前被编辑的管理员id
//            'department_id' => 'require', // 部门id
//            'role_id' => 'require', // 角色id
//            'data_permission' => 'require', // 数据权限
//        ];
        // 验证密码
//        $password = $request->post('password');
//        if ($param['is_merchandiser']){
//            $is_merchandiser= json_encode($param['is_merchandiser']);
//        }else{
//            if ($param['is_merchandiser'] == 0){
//                $merchandiser_id = WaAdmins::find(['merchandiser_id' => $param['admin_id']]);
//                $merchandiser_id = json_decode($merchandiser_id);
//                if($merchandiser_id){
//                    return IndexController::errored($merchandiser_id, '还有其它管理员绑定该跟单人员，暂时无法修改是不是跟单人员');
//                }

//            }
//            $is_merchandiser = 0;
//        }
        $data = [
            'username' => $param['username'], // 用户名
            'nickname' => $param['nickname'], // 昵称
//            'password' => Util::passwordHash($password), // 密码
//            'avatar' => $param['avatar'], // 头像
            'email' => $param['email'], // 邮箱
            'mobile' => $param['mobile'], // 手机
            'updated_at' => date('Y-m-d H:i:s', time()), // 创建时间
            'department_id' => intval($param['department_id']), // 部门id
            'role_id' => $param['role_id'], // 角色id
            'data_permission' => intval($param['data_permission']), // 数据权限
            'is_principal' => intval($param['is_principal']), // 是否是部门负责人
//            'merchandiser_id' => intval($param['merchandiser_id']), // 绑定的跟单人员
//            'is_merchandiser' => $is_merchandiser, // 是否跟单人员 0 不是 1 是
        ];
        if (array_key_exists('nickname_abbreviation',$param)){
            $data['nickname_abbreviation'] = $param['nickname_abbreviation'];
        }
        if (array_key_exists('english_name',$param)){
            $data['english_name'] = $param['english_name'];
        }
        if ($param['status']) {
            $data['status'] = $param['status']; // 1禁用
        }

        // 判断是否是部门负责人 (部门暂时可以没有负责人)
        if (intval($param['is_principal']) == 1){
            $condition_principal= ['department_id' => intval($param['department_id']),'is_principal' => 1];
            $is_principal = WaAdmins::find($condition_principal);
            $is_principal = json_decode($is_principal);
            if ($is_principal){
                //判断部门负责人是否是当前用户
                if(intval($is_principal->id)  != intval($param['admin_id'])){
                    //去掉原来的部门负责人
                    WaAdmins::updated(['department_id' => intval($param['department_id']),'is_principal' => 1],['is_principal'=>0]);
                }
            }
        }

//        $validate = \Tinywan\Validate\Facade\Validate::rule($rule);
//        if (!$validate->check($param)) {
//            return IndexController::errored($validate->getError());
//        } else {
            // 判断用户名是否重复
            $where = ['username' => $param['username']];
            $find = WaAdmins::find($where);
            $find = json_decode($find);
            if ($find) {
                if (property_exists($find, 'id')) {
                    if (intval($param['admin_id']) != intval($find->id)) {
                        return IndexController::errored('', '管理员创建失败,用户名已存在');
                    }
                }
            }



            $condition = [];
            $condition [] = ['id', '=', intval($param['admin_id'])];
            $res = WaAdmins::updated($condition, $data);
            if ($res) {
                return IndexController::successed($res, '管理员更新成功');
            } elseif ($res == 0) {
                return IndexController::successed($res, '管理员更新成功');
            } else {
                return IndexController::errored($res, '管理员创建失败');
            }
//        }
    }

    /**
     * 管理员-删除
     * @param Request $request
     * @return \support\Response
     */
    public function adminDel(Request $request)
    {
        process($request);
        $param = $request->all();
        if ($param['admin_id'] == 1){
            return IndexController::errored('', '超管无权删除');
        }
        $condition = [];
        $condition [] = ['id', '=', $param['admin_id']];
        $data = ['status' => 4]; // 0 正常 1 禁用 4 删除
        $rule = WaAdmins::updated($condition, $data);
        return IndexController::successed($rule, '账户列表');
    }

    /**
     * 管理员-详情
     * @param Request $request
     * @return \support\Response
     */
    public function adminDetail(Request $request)
    {
        process($request);
        $param = $request->all();
        $condition = [];
        $condition [] = ['id', '=', $param['admin_id']];
        $rule = WaAdmins::find($condition);
        $rule = json_decode($rule);
        $rule->role_id = json_decode($rule->role_id);
        $rule = json_encode($rule);
        return IndexController::successed($rule, '账户信息');
    }

    /**
     * 管理员-禁用-启用
     * @param Request $request
     * @return \support\Response
     */
    public function adminForbidden(Request $request)
    {
        process($request);
        $param = $request->all();
        if ($param['admin_id'] == 1){
            return IndexController::errored('', '超管无权禁用');
        }
        $condition = [];
        $condition [] = ['id', '=', $param['admin_id']];
        if ($param['status'] == 1){
            $status = 1;
        }elseif($param['status'] == 0){
            $status = 0;
        }else{
            return IndexController::errored('', '状态值传参有误');
        }
        $data = [
            'status' => $status,// 0 正常 1 禁用 4 删除
            'updated_at' => date('Y-m-d H:i:s', time()), // 更新时间
        ];
        $rule = WaAdmins::updated($condition, $data);
        return IndexController::successed($rule, '账户列表');
    }

    /**
     * 管理员-重置密码
     * @param Request $request
     * @return \support\Response
     */
    public function resetPasswords(Request $request)
    {
//        process($request);
        $param = $request->all();

        /**
         * 验证规则
         */
        $rule = [
            'password' => 'require|max:30', // 密码
            'admin_id' => 'require', // 当前被编辑的管理员id
        ];
        // 验证密码
//        $password = $request->post('password');

        $password = '123456';
        $update_data = [
            'password' => Util::passwordHash($password),
            'updated_at' => date('Y-m-d H:i:s', time()), // 更新时间
        ];

        $condition = ['id' => intval($param['admin_id'])];
        $res = WaAdmins::updated($condition, $update_data);
        if ($res) {
            return IndexController::successed($res, '重置密码成功');
        }else {
            return IndexController::errored($res, '重置密码失败');
        }
    }


    /**
     * 管理员-修改密码
     * @param Request $request
     * @return \support\Response
     */
    public function changePasswords(Request $request)
    {
//        process($request);
        $param = $request->all();

        /**
         * 验证规则
         */
        $rule = [
            'old_password' => 'require|max:30', // 旧密码
            'new_password' => 'require|max:30', // 新密码
            'ready_password' => 'require|max:30', // 确认密码密码
            'admin_id' => 'require', // 当前被编辑的管理员id
        ];
        // 验证密码
//        $password = $request->post('password');

        if ($param['old_password'] == $param['new_password']){
            return IndexController::errored('','旧密码与新密码一致');
        }

        if ($param['new_password'] != $param['ready_password']){
            return IndexController::errored('','新密码与确认密码不一致');
        }

        $admin = Admin::where(['id' => $param['admin_id']])->first();
        if (!$admin) {
            return IndexController::errored('', '账户不存在');
        }
        if (!Util::passwordVerify($param['old_password'], $admin->password)) {
            return IndexController::errored('', '旧密码不正确');
        }

        $password = $param['new_password'];
        $update_data = [
            'password' => Util::passwordHash($password),
            'updated_at' => date('Y-m-d H:i:s', time()), // 更新时间
        ];

        $condition = ['id' => intval($param['admin_id'])];
        $res = WaAdmins::updated($condition, $update_data);
        if ($res) {
            return IndexController::successed($res, '修改密码成功');
        }else {
            return IndexController::errored($res, '修改密码失败');
        }
    }



    /**
     * 部门所有人
     * @param Request $request
     * @return mixed
     */
    public function adminByDepartment(Request $request)
    {
//        process($request);
        $param = $request->all();
        $condition = [];
        if ($param['department_id']) {
            $condition [] = ['department_id', '=', $param['department_id']];
        }
        $fields = ['id','nickname'];

        $rule = WaAdmins::allId($fields, $condition);
        return IndexController::successed($rule, '部门所有人');
    }



    /**
     * 关联跟单人员
     * @param Request $request
     * @return mixed
     */
    public function relevanceMerchandiser(Request $request)
    {
        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        $condition = [];
//        $condition [] = ['is_merchandiser','=',1]; // 是否跟单人员 0 不是 1 是
        $res = WaAdmins::all('*',$condition);
        return IndexController::successed($res, '关联跟单人员列表');
    }



}